import { FC, useCallback, useEffect, useMemo } from "react";
import { Checkbox, Popconfirm, Space } from "antd";
import { get, isNil, isString, set } from "lodash";
import { DeleteOutlined, SettingOutlined } from "@ant-design/icons";

type Props = {
  value?: Record<string, any>[];
  size?: number;
  sourceAtr?: string;
  checkAtr?: string;
  labelAtr?: string;
  onChange?: (v: any) => void;
  onDelete?: (item: any, idx: number) => void;
  onModify?: (item: any, idx: number) => void;
};

const CheckImgList: FC<Props> = ({
  value,
  size = 150,
  sourceAtr = "source",
  checkAtr = "check",
  labelAtr = "label",
  onChange,
  onDelete,
  onModify,
}) => {
  if (!value) return null;
  const needCheckBox = useMemo(
    () => !isNil(get(value, `[0].${checkAtr}`)),
    [value, checkAtr]
  );
  const CheckCtrl = useCallback<FC<{ idx: number }>>(
    ({ idx }) => {
      if (!needCheckBox) return null;
      return (
        <Checkbox
          onChange={(e) => {
            const newVal = [...value];
            set(newVal, `[${idx}].${checkAtr}`, e.target.checked);
            onChange?.(newVal);
          }}
        />
      );
    },
    [needCheckBox, value, checkAtr]
  );
  const Action = useCallback<
    FC<{
      source: any;
      idx: number;
    }>
  >(
    ({ source: item, idx }) => {
      if (!onDelete && !onModify) return null;
      return (
        <Space className="flex-1 justify-end">
          {onModify && <SettingOutlined onClick={() => onModify(item, idx)} />}
          {onDelete && (
            <Popconfirm
              title="删除"
              onConfirm={() => onDelete?.(item, idx)}
              okText="确定"
              cancelText="取消"
            >
              <DeleteOutlined />
            </Popconfirm>
          )}
        </Space>
      );
    },
    [onDelete, onModify]
  );
  return (
    <div className="m-[-15px] mt-[-10px] flex w-full flex-wrap">
      {value.map((item, idx) => (
        <div
          className={`relative m-[15px] inline-block`}
          style={{ width: size, height: size }}
        >
          <img
            src={get(item, sourceAtr, "")}
            alt="图片示例"
            style={{ width: size, height: size, objectFit: "contain" }}
          />
          <div className="absolute inset-x-0 bottom-0 flex items-center bg-[rgba(0,0,0,.7)] p-[5px] text-[rgb(255,255,255)]">
            <CheckCtrl idx={idx} />
            <div className="flex-1 truncate">{item[labelAtr]}</div>
            <Action source={item} idx={idx} />
          </div>
        </div>
      ))}
    </div>
  );
};

export default CheckImgList;
